package com.hourses.controller;

import com.google.code.kaptcha.Producer;
import com.hourses.pojo.*;
import com.hourses.service.UserService;
import com.hourses.service.impl.AuthServiceImpl;
import com.hourses.utils.DigestUtil;
import com.hourses.utils.TokenUtils;
import com.hourses.utils.WarehouseConstants;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/4/25 23:01
 */
@RestController
public class LoginController {
    @Autowired
    private Producer producer;       //生成验证码图片的对象

    @Autowired
    private StringRedisTemplate redisTemplate;

    //生成验证码的接口
    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            //生成验证码图片的文本
            String text = producer.createText();
            //生成验证码图片
            BufferedImage image = producer.createImage(text);
            //将验证码图片保存到redis中去
            redisTemplate.opsForValue().set(text,"",60*2, TimeUnit.SECONDS);//两分钟以后失效

            //将验证码图片相应到前端去
            //设置相应正文“img/jpeg”
            response.setContentType("image/jpeg");
            //将验证码写给前端
            out = response.getOutputStream();
            ImageIO.write(image,"jpg",out);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    //登陆操作的接口    http://localhost:3000/api/login
    @Autowired
    private UserService userService;

    @Autowired
    private TokenUtils tokenUtils;
    @PostMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){
        //先判断验证码正不正确
        String verificationCode = loginUser.getVerificationCode();
        if (!redisTemplate.hasKey(verificationCode)){
            return Result.err(Result.CODE_ERR_BUSINESS,"验证码错误");
        }
        //验证码正确，执行以下操作
        //查询用户
        User user = userService.selectByCode(loginUser.getUserCode());
        //用户是否存在
        if (user!=null){
            //用户存在，判断用户是否已经审核（user_state字段）   0 未审核 、1 已审核
            if (user.getUserState().equals(WarehouseConstants.USER_STATE_PASS)){
                //用户已审核
                //判断用户密码是否正确
                //数据库中的密码是加密过的，但是加密算法只能进行加密，不能进行解密，所以将前端传过来的密码进行加密再进行对比
                String pwd = DigestUtil.hmacSign(loginUser.getUserPwd());
                //判断用户输入的密码是否正确
                if (pwd.equals(user.getUserPwd())){
                    //密码正确
                    //生成jwt Token并存储到redis中去
                    CurrentUser currentUser = new CurrentUser(user.getUserId(),user.getUserCode(),user.getUserName());
                    String token = tokenUtils.loginSign(currentUser, user.getUserPwd());//loginSign方法把token也存储到了redis中去了
                    return Result.ok("登陆成功！",token);

                }else {
                    //密码错误
                    return Result.err(Result.CODE_ERR_BUSINESS,"密码错误!");
                }
            }else {
                return Result.err(Result.CODE_ERR_BUSINESS,"用户未审核!");
            }
        }else {
            //用户不存在
            return Result.err(Result.CODE_ERR_BUSINESS,"用户不存在!");
        }
    }

    //在首页面展示用户名字的接口
    @GetMapping("/curr-user")
    public Result currUser(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){//参数：获取请求路径当中的token
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);//根据token解析token当中的用户信息
        return Result.ok(currentUser);
    }

    //展示权限列表的接口http://localhost:3000/api/user/auth-list
    @Autowired
    private AuthServiceImpl authService;
    @GetMapping("/user/auth-list")
    public Result authList(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        CurrentUser user = tokenUtils.getCurrentUser(token);
        int userId = user.getUserId();
        List<Auth> authTree = authService.getAuthTree(userId);
        return Result.ok(authTree);
    }

    //退出登录的接口 http://localhost:3000/api/logout
    @RequestMapping("/logout")
    public Result logout(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        //从缓存中删除token即可
        Boolean flag = redisTemplate.delete(token);
        if (flag){
            return Result.ok("您已退出登录!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"退出登陆失败！");
    }
}
